--local get_headers = ngx.req.get_headers
--local ua = ngx.var.http_user_agent
--local uri = ngx.var.request_uri
--local url = ngx.var.host .. uri
local redis = require "redis-util"

-- 指定 redis 环境变量 设定默认值
local redisIp = "172.17.0.1"
local redisPort = 6379
local redisPass = nil
local redisDbIndex = 0
local redisKeyWhiteIp = "unite:app:white:ips"

-- 从环境变量中尝试获取参数，若有定义则会覆盖
if os.getenv("ENV_REDIS_IP") ~= nil then
    redisIp = os.getenv("ENV_REDIS_IP")
end

if os.getenv("ENV_REDIS_PASS") ~= nil then
    redisPass = os.getenv("ENV_REDIS_PASS")
end

if os.getenv("ENV_REDIS_PORT") ~= nil then
    redisPort = tonumber(os.getenv("ENV_REDIS_PORT"))
end

if os.getenv("ENV_REDIS_DB_INDEX") ~= nil then
    redisDbIndex = tonumber(os.getenv("ENV_REDIS_DB_INDEX"))
end

if os.getenv("ENV_REDIS_KEY_WHITE_IPS") ~= nil then
    redisKeyWhiteIp = os.getenv("ENV_REDIS_KEY_WHITE_IPS")
end

-- 连接 redis
local red = redis:new({
    host= redisIp,
    port= redisPort,
    db_index= redisDbIndex,
    password= redisPass,
    timeout=1000,
    keepalive=60000,
    pool_size=100
});

-- 验证 redis 是否正常
if red == nil then
    ngx.status = 403
    ngx.say("403 Request is limited (redis is not ok) ")
    ngx.exit(403)
end

-- 验证当前 redis-key 是否存在
local hasKey = red:exists(redisKeyWhiteIp);
if tonumber(hasKey) ~= 1 then
    ngx.status = 403
    ngx.say("403 Request is limited (redisDbIndex "..tostring(redisDbIndex).." not find) ")
    ngx.exit(403)
end

-- 获取当前客户端IP
function getClientIp()
    IP = ngx.req.get_headers()["X-Real-IP"]
    if IP == nil then
        IP = ngx.req.get_headers()["x_forwarded_for"]
    end
    if IP == nil then
        IP  = ngx.var.remote_addr
    end
    if IP == nil then
        IP  = "unknown"
    end
    return IP
end

-- 获取当前IP
local clientIp = getClientIp();
-- 获取 redis 的值
local hasIP = red:sismember(redisKeyWhiteIp,clientIp);

-- 确认白名单redis-key中是否存在当前IP
if tonumber(hasIP) == 1 then
    ngx.exit(0)
else
    ngx.status = 403
    ngx.say("403 Request is limited (whiteList not fond) clientIp=".. clientIp)
    ngx.exit(403)
end
